<?php
// 竞拍
class AuctionAction extends CommonAction{
	//列表
	public function index() 
	{
		$auction_name = trim($_REQUEST['auction_name']);
		$auction_status = trim($_REQUEST['auction_status']);
		$auction_type = trim($_REQUEST['auction_type']);
		$billing_type = trim($_REQUEST['billing_type']);
		$validity_status = trim($_REQUEST['validity_status']);
		
		if(!empty($auction_name))
		{
			$this->assign("auction_name",$auction_name);
			$where.=" and name like %$auction_name%'";
			$parameter .= "auction_name=" . urlencode($auction_name)."&";
		}
		
		if($auction_status != "" && $auction_status >= 0)
		{
			$time = gmtTime();
			
			switch($auction_status)
			{
				case 0:
					$where.=" and (begin_time = 0 or begin_time <= $time) and (end_time = 0 or end_time > $time)";
				break;
				case 1:
					$where.=" and (begin_time > 0 and begin_time > $time)";
				break;
				case 2:
					$where.=" and (end_time > 0 and end_time <= $time)";
				break;
			}

			$parameter .= "auction_status=" . $auction_status ."&";
			$this->assign("auction_status",$auction_status);
		}
		else
		{
			$this->assign("auction_status",-1);
		}
		
		if($validity_status != "" && $validity_status >= 0)
		{
			$time = gmtTime();
			
			switch($validity_status)
			{
				case 0:
					$where.=" and (validity_begin_time = 0 or validity_begin_time <= $time) and (validity_end_time = 0 or validity_end_time > $time)";
				break;
				case 1:
					$where.=" and (validity_begin_time > 0 and validity_begin_time > $time)";
				break;
				case 2:
					$where.=" and (validity_end_time > 0 and validity_end_time <= $time)";
				break;
			}

			$parameter .= "validity_status=" . $validity_status ."&";
			$this->assign("validity_status",$validity_status);
		}
		else
		{
			$this->assign("validity_status",-1);
		}
		
		if($auction_type != "" && $auction_type >= 0)
		{
			$where.=" and auction_type = ".$auction_type;
			$parameter .= "auction_type=" . $auction_type ."&";
			$this->assign("auction_type",$auction_type);
		}
		else
		{
			$this->assign("auction_type",-1);
		}
		
		if($billing_type != "" && $billing_type >= 0)
		{
			$where.=" and billing_type = ".$billing_type;
			$parameter .= "billing_type=" . $billing_type ."&";
			$this->assign("billing_type",$billing_type);
		}
		else
		{
			$this->assign("billing_type",-1);
		}
		
		
		$sql_str = 'SELECT * FROM '.C("DB_PREFIX").'auction where 1'.$where;

		$voList = $this->_Sql_list(M(), $sql_str, "&".$parameter, 'id', false);

		$this->display ('index');
	}
	
	public function add()
	{
		$adv_positions = D("AdvPosition")->findAll();
		$this->assign("adv_positions",$adv_positions);
		
		$new_sort = D('Auction')->max("sort") + 1;
		$this->assign('new_sort',$new_sort);
		$this->assign('ratio',D('Bbs')->getECRatio());
		$this->getAuctionCity(0);
		$this->assign("is_all_city",1);
		$this->display();
	}

	public function insert()
	{
		$name=$this->getActionName();
		$model = D ($name);
		
		if($_POST['auction_type'] == 0)
		{
			$_POST['rec_id'] = $_POST['rec_ad_id'];
			$_POST['rec_data'] = $_POST['rec_ad_data'];
			$_POST['rec_attr'] = serialize($_POST['rec_attr']);
		}
		else
		{
			$_POST['rec_id'] = 0;
			$_POST['rec_data'] = $_POST['rec_index_data'];
			$_POST['rec_attr'] = '';
		}
		
		if($_POST['billing_type'] == 0)
			$_POST['pre_pay'] = floatval($_POST['pre_pay']);
		else
			$_POST['pre_pay'] = 0;
		
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		$upload_list = $this->uploadFile(0,"auction");
		if($upload_list)
			$model->img = $upload_list[0]['recpath'].$upload_list[0]['savename'];
		
		//保存当前数据对象
		$list=$model->add ();
		if ($list!==false) { //保存成功
			$this->updateAuctionCity($list);
			$this->saveLog(1,$list);
			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('ADD_SUCCESS'));
		} else {
			//失败提示
			$this->saveLog(0,$list);
			$this->error (L('ADD_FAILED'));
		}
	}
	
	public function edit()
	{		
		$name=$this->getActionName();
		$model = M ( $name );
		$id = $_REQUEST [$model->getPk ()];
		$vo = $model->getById ( $id );
		if(!empty($vo['rec_attr']))
		{
			$rec_attr = unserialize($vo['rec_attr']);
			$this->assign ('rec_attr', $rec_attr);	
		}
		
		$this->assign ('time',gmtTime());
		$this->assign ('vo', $vo);
		$this->assign('ratio',D('Bbs')->getECRatio());
		$this->getAuctionCity($id);
		$adv_positions = D("AdvPosition")->findAll();
		$this->assign("adv_positions",$adv_positions);
		$this->display();
	}
	
	public function update() {
		$name=$this->getActionName();
		$model = D ( $name );
		$id = $_REQUEST[$model->getPk()];
		
		$_POST['auction_status'] = isset($_POST['auction_status']) ? intval($_POST['auction_status']) : 0;
		if(!empty($_POST['rec_attr']))
		{
			$_POST['rec_attr'] = serialize($_POST['rec_attr']);
		}
		
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		$upload_list = $this->uploadFile(0,"auction");
		if($upload_list)
		{			
			$map[$model->getPk()] = $id;
			$item = $model->where($map)->find();
			@unlink($this->getRealPath().$item['img']);
			$model->img = $upload_list[0]['recpath'].$upload_list[0]['savename'];
		}
			
		// 更新数据
		$list=$model->save ();
		if (false !== $list)
		{
			//成功提示
			@unlink($this->getRealPath()."/public/auction/auction/".$id.".fanwe");
			$this->updateAuctionCity($id);
			
			
			$this->saveLog(1);
			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('EDIT_SUCCESS'));
		}
		else
		{
			//错误提示
			$this->saveLog(0);
			$this->error (L('EDIT_FAILED'));
		}
	}
	
	public function foreverdelete() {
		//删除指定记录
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			
			if (isset ( $id )) {
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				$items = $model->where($condition)->findAll();	
				foreach($items as $item)
				{
					$this->emptyAuction($item['id']);
					@unlink($this->getRealPath().$item['img']);
				}

				if (false !== $model->where ( $condition )->delete ()) {
					$this->saveLog(1);
					$this->success (L('DEL_SUCCESS'));
				} else {
					$this->saveLog(0);
					$this->error (L('DEL_FAILED'));
				}
			} else {
				$this->saveLog(0);
				$this->error ( L('INVALID_OP') );
			}
		}
		$this->forward ();
	}
	
	public function updateHot()
	{
		$id = intval($_REQUEST['id']);
		$is_hot = D("Auction")->where('id='.$id)->getField("is_hot");
		
		if($is_hot == 0)
			$is_hot = 1;
		else
			$is_hot = 0;
			
		if(D("Auction")->where('id='.$id)->setField("is_hot",$is_hot))
			echo $is_hot;
		else
			echo "err";
	}
	
	public function deleteImg()
	{
		$a_id = intval($_REQUEST['id']);
		$a_info = D("Auction")->getById($a_id);
		if($a_info['img']!="")
		{
			@unlink($this->getRealPath().$a_info['img']);
			D("Auction")->where("id=".$a_id)->setField("img","");
		};
	}

	public function resetAuction()
	{
		$id = intval($_REQUEST['id']);
		if($id > 0)
			$this->emptyAuction($id);
		
		M()->query("UPDATE ".C('DB_PREFIX')."auction SET user_id = 0,auction_status = 0 WHERE id = $id");

		$this->index();
	}

	private function emptyAuction($id)
	{
		$prefix = C('DB_PREFIX');
		$auction = D("Auction")->where("id=".$id)->find();
		
		$statistic = M("AuctionStatistic")->where("auction_id = $id")->find();
		if($statistic)
		{
			if($auction['billing_type'] == 0)
			{
				$money = $statistic['freeze_money'] - $statistic['outlay_money'];
				if($money > 0)
				{
					D('User')->updateUserScore($auction['user_id'],$id,'Admin','Auction',$money,'退回推广 '.$auction['name'].',冻结剩余积分',true);
				}
			}
			M()->query("DELETE FROM ".$prefix."auction_statistic WHERE auction_id = $id");
		}
		else
		{
			$freeze_money = M("FreezeMoney")->where("auction_id = $id")->find();
			if($freeze_money)
			{
				D('User')->updateUserScore($freeze_money['uid'],$id,'Admin','Auction',$money,'退回推广 '.$auction['name'].',冻结剩余积分',true);
			}
		}
		M()->query("DELETE FROM ".$prefix."freeze_money WHERE auction_id = $id");
		M()->query("DELETE FROM ".$prefix."auction_bid WHERE auction_id = $id");
		M()->query("DELETE FROM ".$prefix."auction_city_goods WHERE auction_id = $id");
		M()->query("DROP TABLE IF EXISTS ".$prefix."auction_click_".$id);
		M()->query("DELETE FROM ".$prefix."auction_log WHERE auction_id = $id");
		M()->query("DELETE FROM ".$prefix."auction_result WHERE auction_id = $id");
		M()->query("DELETE FROM ".$prefix."auction_log WHERE auction_id = $id");
		$adv_list = D("Adv")->where("auction_id = $id AND type IN (1,2)")->findAll();
		foreach($adv_list as $adv)
		{
			@unlink($this->getRealPath().$adv['code']);
		}
		M()->query("DELETE FROM ".$prefix."adv WHERE auction_id = $id");
		M()->query("DELETE FROM ".$prefix."cron WHERE type = 'auction' AND data='$id'");
		@unlink($this->getRealPath()."/public/auction/auction/".$id.".fanwe");
		@unlink($this->getRealPath()."/public/auction/bid/".$id.".fanwe");
		@unlink($this->getRealPath()."/public/auction/rank/".$id.".fanwe");
		@unlink($this->getRealPath()."/public/auction/record/".$id.".fanwe");
		@unlink($this->getRealPath()."/public/auction/auction/".$id.".fanwe");
		@unlink($this->getRealPath()."/public/auction/user/".$id."_".$auction['user_id'].".fanwe");
	}

	
	public function updateAuctionCity($id)
	{
		M('AuctionCity')->where('auction_id = '.$id)->delete();
		$is_all_city = isset($_POST['is_all_city']) ? intval($_POST['is_all_city']) : 0;
		if( $is_all_city == 1)
		{
			$auction_city=array();
			$auction_city['auction_id']= $id;
			$auction_city['city_id'] = 0;
			M('AuctionCity')->add($auction_city);
			
			$sql='SELECT acg.auction_id,acg.site_id,gc.id as city_id,acg.goods_id 
				FROM '.C('DB_PREFIX').'group_city AS gc 
				LEFT JOIN '.C('DB_PREFIX').'auction_city_goods AS acg ON acg.auction_id = '.$id.' AND acg.city_id = gc.id 
				WHERE gc.status = 1';
			$city_list = M()->query($sql);
			
			foreach($city_list as $data)
			{
				M()->query('REPLACE INTO '.C('DB_PREFIX').'auction_city_goods(auction_id,site_id,city_id,goods_id) 
							VALUES('.$id.',\''.$data['site_id'].'\','.$data['city_id'].',\''.$data['goods_id'].'\')');
			}
		}
		else
		{
			$city_ids = $_POST['auction_city'];
			foreach($city_ids as $city_id)
			{
				$auction_city=array();
				$auction_city['auction_id']= $id;
				$auction_city['city_id'] = $city_id;
				M('AuctionCity')->add($auction_city);
				
				$data = M('AuctionCityGoods')->where('auction_id = '.$id.' AND city_id = '.$city_id)->find();
				if(!isset($data['site_id']))
					$data['site_id'] = 0;
					
				if(!isset($data['goods_id']))
					$data['goods_id'] = 0;
						
				M()->query('REPLACE INTO '.C('DB_PREFIX').'auction_city_goods(auction_id,site_id,city_id,goods_id) 
							VALUES('.$id.','.$data['site_id'].','.$city_id.','.$data['goods_id'].')');
			}
		}
	}
	
	public function getAuctionCity($id)
	{
		$is_all_city = M('AuctionCity')->where("auction_id = $id AND city_id = 0")->count();
		if($is_all_city > 0)
			$this->assign("is_all_city",1);
			
		$sql='SELECT gc.id,gc.name,gc.py_t,IF(ac.auction_id IS NOT NULL,1,0) AS is_city 
				FROM '.C('DB_PREFIX').'group_city AS gc 
				LEFT JOIN '.C('DB_PREFIX').'auction_city AS ac ON ac.city_id = gc.id AND ac.auction_id = '.$id.' 
				WHERE gc.status = 1 AND gc.py <> \'china\' GROUP BY gc.id ORDER BY gc.sort ASC,gc.id ASC';
	
		$city_list = M()->query($sql);
		$citys=array();
		foreach($city_list as $k=>$v)
		{
			$v['py_t'] = strtoupper($v['py_t']);
			
			if($v['py_t'] >= 'A' && $v['py_t'] <= 'G')
				$citys['A-G'][] = $v;
				
			if($v['py_t'] >= 'H' && $v['py_t'] <= 'N')
				$citys['H-N'][] = $v;
				
			if($v['py_t'] >= 'O' && $v['py_t'] <= 'T')
				$citys['O-T'][] = $v;
				
			if($v['py_t'] >= 'U' && $v['py_t'] <= 'Z')
				$citys['U-Z'][] = $v;
		}
		
		ksort($citys);
		
		$this->assign("auction_citys",$citys);
	}
}

function getResetLink($id,$status)
{
	if($status == 1)
		return '<a href="'.U('auction/resetAuction',array('id'=>$id)).'" onclick="return resetHandler();">重置</a>';
	else
		return '';
}

function getAuctionType($type)
{
	$types = array(
		'0'=>'广告位',
		'1'=>'团购排序',
	);
	
	return $types[$type];
}

function getBillingType($type)
{
	$types = array(
		'0'=>'点击付费',
		'1'=>'固定费用',
	);
	
	return $types[$type];
}
?>